package com.zige.zige.task;

import android.app.Activity;
import android.content.Intent;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.zige.zige.activity.NetErrorActivity;
import com.zige.zige.utils.ToastUtils;

import java.util.Map;

/**
 * Created by kim on 2015/4/7.
 *
 */
public abstract class PostRequestTask extends ITask {

    RequestQueue requestQueue;

    protected PostRequestTask(Map<String, String> params, Activity context, String url) {
        this.params = params;
        this.context = context;
        this.url = url;
    }

    @Override
    public void handleTask() {
        requestQueue= Volley.newRequestQueue(context);
        StringRequest stringRequest=new StringRequest(
                Request.Method.POST,
                url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        handleResponse(response);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
//                        ToastUtils.showToast(context, "网络连接失败");
//                        context.startActivity(new Intent(context, NetErrorActivity.class));
                        handleError();
                    }
                }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return super.getHeaders();
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(stringRequest);
    }

    protected void handleError(){

    }

    protected abstract void handleResponse(String response);

    public void stop(){
        requestQueue.cancelAll(context);
    }
}
